package com.hrt.datasender.web.calSetting;

import com.btcode.db.sqlparameter.SQLParameterList;
import com.btcode.orm.model.ModelPageResult;
import com.hrt.db.DBManager;

import java.util.*;

public final class CalSettingService {

    private static volatile CalSettingService instance;

    /**
     * 防止每次都要查询sqlite表,一小时更新一次
     */
    public List<BdCalTimeModel> calTimeModels;

    private CalSettingService() {
        calTimeModels = getHelpfulList();
    }

    public static CalSettingService getInstance() {
        if (instance == null) {
            synchronized (CalSettingService.class) {
                if (instance == null) {
                    instance = new CalSettingService();
                }
            }
        }
        return instance;
    }

    public BdCalTimeModel create(BdCalTimeModel model) {
        model.setId(UUID.randomUUID().toString());
        model.setCreatetime(new Date());
        String sql = "delete from BD_CAL_TIME where PARAM_CODE_BUS = @PARAM_CODE_BUS";
        SQLParameterList pc = new SQLParameterList();
        pc.put("PARAM_CODE_BUS", model.getParamCodeBus());
        DBManager.getDataExecuter().delete(sql,pc);
        DBManager.getORMExecuter().create(model);
        updateCalTime();
        return model;
    }

    public List<BdCalTimeModel> getList() {
        return DBManager.getORMExecuter().getModelList(BdCalTimeModel.class, null,null).getData();
    }

    public List<BdCalTimeModel> getHelpfulList() {
        ModelPageResult mpr = DBManager.getORMExecuter().getModelList(BdCalTimeModel.class, null,null);
        List<BdCalTimeModel> models = mpr.getData();
        List<BdCalTimeModel> result = new ArrayList<>();
        Date date = new Date();
        for(BdCalTimeModel model :models){
            if(date.compareTo(model.getEndTime())<=0&&date.compareTo(model.getStartTime())>=0){
                result.add(model);
            }
        }
        return result;
    }

    public void updateCalTime() {
        calTimeModels = getHelpfulList();
    }

    public String isCalData(Date date,String param) {
        String flag = "N";
        for(BdCalTimeModel model :calTimeModels){
            if(param.equals(model.getParamCodeBus())){
                Date start =model.getStartTime();
                Date end = model.getEndTime();
                if(date.compareTo(start)>=0&&date.compareTo(end)<=0){
                    return  "C";
                }
            }
        }
        return flag;
    }
}